package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryWithCache() {
        //1.先查询redis有没有数据
        String key= "shop:type";
        List<String> typeList = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.存在数据，返回
        if(!typeList.isEmpty()){
            log.info("redis中有数据！");
            List<ShopType> list=new ArrayList<>();
            for (String type : typeList) {
                ShopType shopType = JSONUtil.toBean(type, ShopType.class);
                list.add(shopType);
            }
            return Result.ok(list);
        }
        //3.redis不存在数据，查询数据库
        List<ShopType> list = query().orderByAsc("sort").list();
        //4.数据库也没有，返回错误
        if(list.isEmpty()){
            return Result.fail("店铺类型不存在！");
        }
        //5.数据库里有，将数据加入redis
        log.info("店铺类型加入redis!");
        List<String> strings=new ArrayList<>();
        for (ShopType shopType : list) {
            strings.add(JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.opsForList().rightPushAll(key,strings);
        //6.返回数据
        return Result.ok(list);
    }
}
